﻿using System.CodeDom;
using System.Collections.Generic;
using System.Linq;

namespace WeaverCustomTool
{
    public struct MethodDeclaration
    {
        private readonly CodeTypeDeclaration type;

        /// <summary>
        /// Initializes a new instance of the <see cref="MethodDeclaration" /> struct.
        /// </summary>
        /// <param name="type">The type.</param>
        public MethodDeclaration(CodeTypeDeclaration type)
        {
            this.type = type;
        }

        /// <summary>
        /// Gets the method from its name or get null.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        public CodeMemberMethod GetMethodOrDefault(string name, params CodeParameterDeclarationExpression[] parameters)
        {
            if(type != null)
            {
                var method = type.Members.OfType<CodeMemberMethod>().FirstOrDefault(
                    m => m.Name == name
                         && m.Parameters.Count == parameters.Count()
                         && parameters.SequenceEqual(m.Parameters.OfType<CodeParameterDeclarationExpression>(), new CodeParameterDeclarationExpressionComparer()));

                return method;
            }

            return null;
        }
    }

    public class CodeParameterDeclarationExpressionComparer: IEqualityComparer<CodeParameterDeclarationExpression>
    {
        public bool Equals(CodeParameterDeclarationExpression x, CodeParameterDeclarationExpression y)
        {
            return  x == y || x.Type.ToString() == y.Type.ToString();
        }

        public int GetHashCode(CodeParameterDeclarationExpression obj)
        {
            return obj.Type.ToString().GetHashCode();
        }
    }
}
